<?php

class UsersController extends ProjectController
{

	

	public function actionLogin(){
		$this->layout = "blank";
		if(!empty($_POST)){
			if(!empty($_POST['FormLogin']['rememberMe']) && $_POST['FormLogin']['rememberMe']=='on' ) $_POST['FormLogin']['rememberMe'] = 1;
			else $_POST['FormLogin']['rememberMe'] = 0;
			$model = new FormLogin;
			$data =  @json_decode(CActiveForm::validate($model));
			if(!empty($data)){
				
				jsonOut($data);
			}else{
				$model->attributes = $_POST['FormLogin'];
				if($model->validate() && $model->login()){
					
					jsonOut(array(
						'code'=>200,
						'message'=>_t('Login successfully')
					));
					
				}else{
					jsonOut(array(
						'code'=>404,
						'message'=>_t('Login failer.')
					));
				}
			
			}
			
		
		}else{
		
			$this->render("login");
		}
		
	}
	public function actionRegister(){
		$this->layout = "blank";
		
		if(!empty($_POST)){
			$model=new Users;
			$model->attributes=$_POST['Users'];
			
			
			$data =  @json_decode(CActiveForm::validate($model));
			
			if(!empty($data)){
				
				jsonOut($data);
			}else{
				if($model->validate()){
					$model->password = Users::model()->encodePassword($model->password);
					$model->created = date("Y-m-d G:i:s");
					$groups = Groups::model()->notAdmin();
					$model->group_id = $groups->id;
					if($model->save()){
						
						
						jsonOut(array(
							'code'=>200,
							'message'=>_t('Created an account successfully.')
						));
					}else{
						$errors = $model->getErrors();
						list ($field, $_errors) = each ($errors);
						
						jsonOut(array(
							'code'=>400,
							'message'=> $_errors[0]
						));
					}
				}
				
			}
			
		
		}else{
		
			$this->render("register");
		}
		
	}
	public function actionForgot(){
		$this->layout = "blank";
		if(!empty($_POST)){
			$model = new ForgotPass;
			$data =  @json_decode(CActiveForm::validate($model));
			if(!empty($data)){
				
				jsonOut($data);
			}else{
				$user = Users::model()->findByAttributes(array('email'=>$_POST['ForgotPass']['email']));
				if(empty($user)):
					jsonOut($data);
				else:
					jsonOut(array(
						'code'=>200,
						'message'=>_t('Send message successfully')
					),false);
					Yii::import('ext.yii-mail.*', true);
					$message = new YiiMailMessage;
					$message->setSubject(_t('Reset your Faster Password'));
					$message->view = 'forgot';
					$message->setBody(array('attr'=>$user->attributes), 'text/html');
					$message->addTo($user->email);
					$message->from = Yii::app()->params['adminEmail'];
					Yii::app()->mail->send($message);
				endif;
				
				
			}
			
			
		
		}else{
		
			$this->render("forgot");
		}
		
		
	}

	
	
}
